package com.whl.cloud.config;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.cloud.netflix.zuul.filters.ZuulProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.jdbc.core.JdbcTemplate;

import com.alibaba.druid.pool.DruidDataSource;
import com.whl.cloud.lock.DistributionLockFactory;
import com.whl.cloud.lock.DistributionLockFactory.DistributionLock;
import com.whl.cloud.session.RedisSessionCache;
import com.whl.cloud.session.SessionCache;

@Configuration
public class BeanConfig {

	@Autowired
	private Environment env;
	@Autowired
	ZuulProperties zuulProperties;
	@Autowired
	ServerProperties server;
	@Autowired
	JdbcTemplate jdbcTemplate;

	@Bean
	public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
		RedisTemplate<String, String> template = new RedisTemplate<String, String>();
		template.setConnectionFactory(factory);
		StringRedisSerializer serializer = new StringRedisSerializer();
		template.setKeySerializer(serializer);
		template.setValueSerializer(serializer);
		template.afterPropertiesSet();
		return template;
	}

	@Bean
	public SessionCache sessionCache(RedisTemplate<String, String> redisTemplate) {
		SessionCache sessionCache = new RedisSessionCache(redisTemplate);
		return sessionCache;
	}

	@Bean
	public DistributionLock distributionLock(RedisTemplate<String, String> redisTemplate) {
		DistributionLockFactory distributionLockFactory = new DistributionLockFactory();
		distributionLockFactory.setRedisTemplate(redisTemplate);
		distributionLockFactory.setTryInterval(5000l);
		distributionLockFactory.setTries(3);
		return distributionLockFactory.getObject();
	}

	@Bean
	public DataSource dataSource() {
		DruidDataSource dataSource = new DruidDataSource();
		dataSource.setUrl(env.getProperty("spring.datasource.url"));
		dataSource.setUsername(env.getProperty("spring.datasource.username"));// 用户名
		dataSource.setPassword(env.getProperty("spring.datasource.password"));// 密码
		dataSource.setInitialSize(2);
		dataSource.setMaxActive(20);
		dataSource.setMinIdle(0);
		dataSource.setMaxWait(60000);
		dataSource.setValidationQuery("SELECT 1");
		dataSource.setTestOnBorrow(false);
		dataSource.setTestWhileIdle(true);
		dataSource.setPoolPreparedStatements(false);
		return dataSource;
	}
	
	@Bean
	public CustomRouteLocator routeLocator() {
		CustomRouteLocator routeLocator = new CustomRouteLocator(this.server.getServletPrefix(), this.zuulProperties);
		routeLocator.setJdbcTemplate(jdbcTemplate);
		return routeLocator;
	}

}
